2023/12/231296字符

call & apply

  • call apply 改变this指向 区别:传参列表不同

call 需要把实参按形参的个数传进去

function Person(name, age){
    // .call() 方法会在这里隐式的加入 this == obj
    this.name = name;
    this.age = 100;
}
var person = new Person('deng', 100);
var obj = {}
Person.call(obj);  // this 指向 obj

有效的减少代码量(代码引用)

function Person(name, age, sex){
    this.name = name;
    this.age = age;
    this.sex = sex;
}
function Student(name, age, sex, tel, grade){
    Person.call(this, name, age, sex);
    this.tel = tel;
    this.grade = grade;
}
var student = new Student('wang', 123, 'male', 139, 2019);

apply 需要传一个 arguments

function Student(name, age, sex, tel, grade){
    Person.apply(this, [name, age, sex]);
    this.tel = tel;
    this.grade = grade;
}

手写 call

Function.prototype.myCall = function(ctx, ...args) {
    ctx = [null, undefined].includes(ctx) ? globalThis : Object(ctx);
    const key = Symbol('temp');
    Object.defineProperty(ctx, key, {
        enumerable: false,
        value: this,
    })
    const result = ctx[key](...args);
    delete ctx.fn;
    return result;
}